<template>
  <div class="bg-white rounded-lg shadow-md p-6">
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
      <h2 class="text-xl font-semibold text-gray-800">我的收藏</h2>
      <div class="flex flex-col sm:flex-row gap-2">
        <el-input
          v-model="searchQuery"
          placeholder="搜索收藏内容"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          class="w-full sm:w-60"
        />
        <el-select 
          v-model="sortBy" 
          placeholder="排序方式" 
          @change="handleSort"
          class="w-full sm:w-32"
        >
          <el-option label="最新收藏" value="newest" />
          <el-option label="最早收藏" value="oldest" />
          <el-option label="标题排序" value="title" />
        </el-select>
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="min-h-[400px]" v-loading="loading">
      <!-- 空状态 -->
      <el-empty
        v-if="!loading && favoritesList.length === 0"
        description="暂无收藏内容"
      >
        <template #image>
          <el-icon class="text-6xl text-gray-300"><Star /></el-icon>
        </template>
        <el-button type="primary">浏览文章</el-button>
      </el-empty>

      <!-- 收藏列表 -->
      <template v-else>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div
            v-for="item in favoritesList"
            :key="item.id"
            class="bg-white border border-gray-200 rounded-lg overflow-hidden transition-shadow duration-300 hover:shadow-md"
          >
            <!-- 文章封面 -->
            <div class="relative h-48 overflow-hidden group">
              <img 
                :src="item.cover" 
                :alt="item.title" 
                class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
              >
              <div class="absolute top-2 right-2 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
                <el-button
                  type="danger"
                  size="small"
                  circle
                  @click="handleRemoveFavorite(item.id)"
                  :loading="removingId === item.id"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>

            <!-- 文章信息 -->
            <div class="p-4">
              <h3 class="text-lg font-medium text-gray-800 mb-2 truncate" :title="item.title">
                {{ item.title }}
              </h3>
              <p class="text-sm text-gray-600 mb-4 line-clamp-2">{{ item.summary }}</p>
              <div class="flex items-center text-xs text-gray-500">
                <span class="flex items-center">
                  <el-icon class="mr-1"><Calendar /></el-icon>
                  {{ formatDate(item.favoriteTime) }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="mt-8 flex justify-center">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Star, Delete, Calendar } from '@element-plus/icons-vue'
import { useContentStore } from '../store'

const contentStore = useContentStore()

// 状态
const loading = ref(false)
const removingId = ref(null)
const searchQuery = ref('')
const sortBy = ref('newest')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const favorites = ref([])

// 计算属性
const favoritesList = computed(() => {
  let list = [...favorites.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    list = list.filter(item => 
      item.title.toLowerCase().includes(query) || 
      item.summary.toLowerCase().includes(query)
    )
  }
  
  // 排序
  switch (sortBy.value) {
    case 'newest':
      list.sort((a, b) => new Date(b.favoriteTime) - new Date(a.favoriteTime))
      break
    case 'oldest':
      list.sort((a, b) => new Date(a.favoriteTime) - new Date(b.favoriteTime))
      break
    case 'title':
      list.sort((a, b) => a.title.localeCompare(b.title))
      break
  }
  
  return list
})

// 监听搜索和排序变化，重置页码
watch([searchQuery, sortBy], () => {
  currentPage.value = 1
})

// 初始化
onMounted(() => {
  loadFavorites()
})

// 加载收藏列表
async function loadFavorites() {
  try {
    loading.value = true
    const result = await contentStore.getFavorites(currentPage.value, pageSize.value)
    favorites.value = result.items
    totalItems.value = result.total
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    ElMessage.error('加载收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
function handleSearch() {
  // 搜索逻辑已在计算属性中实现
}

// 处理排序
function handleSort() {
  // 排序逻辑已在计算属性中实现
}

// 处理分页大小变化
function handleSizeChange(size) {
  pageSize.value = size
  loadFavorites()
}

// 处理页码变化
function handleCurrentChange(page) {
  currentPage.value = page
  loadFavorites()
}

// 取消收藏
async function handleRemoveFavorite(id) {
  try {
    await ElMessageBox.confirm(
      '确定要取消收藏这篇文章吗？',
      '取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    removingId.value = id
    await contentStore.removeFavorite(id)
    favorites.value = favorites.value.filter(item => item.id !== id)
    totalItems.value--
    
    ElMessage.success('已取消收藏')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败')
    }
  } finally {
    removingId.value = null
  }
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN')
  } catch (error) {
    return dateString
  }
}
</script>